<template>
  <section class="todoapp">
    <hm-header @add-event="add"></hm-header>
    <hm-main
      :arr="newArr"
      @change-event="change"
      @changeAll-event="changeAll"
      @del-event="del"
    ></hm-main>
    <hm-footer
      :arr="arr"
      @clear-event="clear"
      @check="check"
      :type="type"
    ></hm-footer>
  </section>
</template>

<script>
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  data() {
    return {
      // arr: [
      //   { id: 1, done: false, name: "吃饭" },
      //   { id: 2, done: true, name: "睡觉" },
      //   { id: 3, done: false, name: "打豆豆" },
      // ],
      arr: JSON.parse(localStorage.getItem("arr")) || [],
      type: "all",
    };
  },
  methods: {
    change(id) {
      const obj = this.arr.find((item) => item.id === id);
      obj.done = !obj.done;
    },
    changeAll(value) {
      this.arr.forEach((item) => (item.done = value));
    },
    del(id) {
      this.arr = this.arr.filter((item) => item.id !== id);
    },
    add(value) {
      const obj = { id: +new Date(), done: false, name: value };
      this.arr.unshift(obj);
    },
    clear() {
      this.arr = this.arr.filter((item) => item.done !== true);
    },
    check(value) {
      this.type = value;
    },
  },
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  computed: {
    newArr() {
      if (this.type === "all") {
        return this.arr;
      } else if (this.type === "undone") {
        return this.arr.filter((item) => item.done === false);
      } else {
        return this.arr.filter((item) => item.done === true);
      }
    },
  },
  watch: {
    arr: {
      // immediate: true,
      deep: true,
      handler(newVul) {
        localStorage.setItem("arr", JSON.stringify(newVul));
      },
    },
  },
};
</script>

<style></style>
